/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2021并保留所有权利。
 * Copyright 2021, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.testthread.test.nmn;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.*;

    class Resource
    {
    	private String name;
    	private int count = 1;
    	private boolean flag = false;
    
    //	创建一个锁对象。
    	Lock lock = new ReentrantLock();
    
    	//通过已有的锁获取该锁上的监视器对象。
    //	Condition con = lock.newCondition();
    
    	//通过已有的锁获取两组监视器，一组监视生产者，一组监视消费者。
    	Condition producer_con = lock.newCondition();
    	Condition consumer_con = lock.newCondition();
    
    	
    	public  void set(String name)//  t0 t1
    	{
    		lock.lock();
    		try
    		{
    			while(flag)
    //			try{lock.wait();}catch(InterruptedException e){}//   对比，这是之前的写法
    			try{producer_con.await();}catch(InterruptedException e){}
    		
    			this.name = name + count;//烤鸭1  烤鸭2  烤鸭3
    			count++;//2 3 4
    			System.out.println(Thread.currentThread().getName()+"...生产者5.0..."+this.name);//生产烤鸭1 生产烤鸭2 生产烤鸭3
    			flag = true;

    			consumer_con.signal(); //唤醒对方线程
    		}
    		finally
    		{
    			lock.unlock(); //释放锁
    		}
    		
    	}
    
    	public  void out()// t2 t3
    	{
    		lock.lock();
    		try
    		{
    			while(!flag)
    //			try{this.wait();}catch(InterruptedException e){}	//t2  t3
    			try{
					consumer_con.await();}catch(InterruptedException e){}	//t2  t3
    			System.out.println(Thread.currentThread().getName()+"...消费者.5.0......."+this.name);//消费烤鸭1
    			flag = false;

    			producer_con.signal();
    		}
    		finally
    		{
    			lock.unlock();
    		}
    		
    	}
    }